package com.huhao.wshare.Profile;

import static com.huhao.wshare.Config.DELETE_DYNAMIC_API;
import static com.huhao.wshare.Config.GET_FRIEND_DYNAMIC_API;
import static com.huhao.wshare.Config.RELEASE_DYNAMIC_API;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.huhao.wshare.BaseActivity;
import com.huhao.wshare.Dynamic.Author;
import com.huhao.wshare.Dynamic.Comment;
import com.huhao.wshare.Dynamic.ReleaseDynamicActivity;
import com.huhao.wshare.Dynamic.ZoomedImageAdapter;
import com.huhao.wshare.R;
import com.huhao.wshare.Dynamic.DynamicFragment;
import com.huhao.wshare.Dynamic.DynamicItem;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.SharedPreferences;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.SnapHelper;

public class MyDynamicActivity extends BaseActivity implements ZoomedImageAdapter.OnImageCloseListener{
    private int userId;
    private static final int PAGE_SIZE = 10;
    private RecyclerView rvMyDynamics;
    private MyDynamicAdapter dynamicAdapter;
    private List<DynamicItem> dynamicList = new ArrayList<>();
    private int currentPage = 0;
    private boolean isLastPage = false;
    private OkHttpClient client = new OkHttpClient();
    private TextView tvName;
    private ImageView ivBackground;
    private ImageView ivAvatar;
    private String gender;
    private RecyclerView rvZoomedImages;
    private List<String> currentImageUrls = new ArrayList<>();
    private String token;
    private ImageButton btnAdd;
    private SwipeRefreshLayout swipeRefreshLayout; // 下拉刷新控件
    private boolean isLoading = false; // 加载状态标志

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_dynamic);

        btnAdd = findViewById(R.id.btnAdd);
        btnAdd.setOnClickListener(v -> {
            Intent intent = new Intent(MyDynamicActivity.this, ReleaseDynamicActivity.class);
            startActivity(intent);
        });

        // 从SharedPreferences获取用户信息
        SharedPreferences sp = getSharedPreferences("user_prefs", MODE_PRIVATE);
        userId = sp.getInt("id", -1);
        String username = sp.getString("username", "");
        String avatarUrl = sp.getString("avatar", "");
        String backgroundUrl = sp.getString("bkImg", "");
        gender = sp.getString("gender", "man");
        token = sp.getString("token", null);

        if (userId == -1 || token == null) {
            Toast.makeText(this, "用户信息获取失败", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // 初始化下拉刷新
        swipeRefreshLayout = findViewById(R.id.swipeRefreshLayout);
        swipeRefreshLayout.setOnRefreshListener(this::loadInitialData);

        // 初始化图片预览RecyclerView
        rvZoomedImages = findViewById(R.id.rvZoomedImages);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        rvZoomedImages.setLayoutManager(layoutManager);

        // 添加 PagerSnapHelper 确保滑动对齐
        SnapHelper snapHelper = new PagerSnapHelper();
        snapHelper.attachToRecyclerView(rvZoomedImages);

        // 设置预览RecyclerView点击关闭
        rvZoomedImages.setOnClickListener(v -> {
            rvZoomedImages.setVisibility(View.GONE);
        });

        // 初始化用户信息
        initUserInfoViews(username, avatarUrl, backgroundUrl);
        // 初始化RecyclerView
        initRecyclerView();
        // 加载初始数据
        loadInitialData();
    }

    private void initUserInfoViews(String username, String avatarUrl, String backgroundUrl) {
        // 根据布局文件中的ID获取控件
        tvName = findViewById(R.id.tvName);
        ivBackground = findViewById(R.id.background_image);
        ivAvatar = findViewById(R.id.ivAvatar);

        // 设置用户名
        tvName.setText(username);

        // 设置头像
        int defaultAvatarResId = "woman".equals(gender) ?
                R.drawable.default_avatar_woman : R.drawable.default_avatar_man;

        if (avatarUrl != null && !avatarUrl.isEmpty() && !avatarUrl.equals("null")) {
            Glide.with(this)
                    .load(avatarUrl)
                    .apply(RequestOptions.circleCropTransform())
                    .placeholder(defaultAvatarResId)
                    .error(defaultAvatarResId)
                    .into(ivAvatar);
        } else {
            ivAvatar.setImageResource(defaultAvatarResId);
        }

        // 设置背景图
        if (backgroundUrl != null && !backgroundUrl.isEmpty() && !backgroundUrl.equals("null")) {
            Glide.with(this)
                    .load(backgroundUrl)
                    .into(ivBackground);
        } else {
            ivBackground.setImageResource(R.drawable.default_background);
        }
    }

    private void initRecyclerView() {
        rvMyDynamics = findViewById(R.id.rvMyDynamics);
        dynamicAdapter = new MyDynamicAdapter(
                this,
                dynamicList,
                (imageUrls, position) -> {
                    currentImageUrls = imageUrls;
                    rvZoomedImages.setAdapter(new ZoomedImageAdapter(this, imageUrls, this));
                    if (rvZoomedImages.getLayoutManager() instanceof LinearLayoutManager) {
                        ((LinearLayoutManager) rvZoomedImages.getLayoutManager()).scrollToPositionWithOffset(position, 0);
                    }
                    rvZoomedImages.setVisibility(View.VISIBLE);
                },
                (dynamicId, position) -> {
                    deleteDynamic(dynamicId, position);
                },
                (dynamicId, position, isLiked) -> {
                    likeDynamic(dynamicId, position, isLiked);
                },
                (dynamicId, position, commentContent) -> {
                    sendComment(dynamicId, position, commentContent);
                },
                (commentId, dynamicPosition, commentPosition) -> {
                    deleteComment(commentId, dynamicPosition, commentPosition);
                }
        );
        rvMyDynamics.setLayoutManager(new LinearLayoutManager(this));
        rvMyDynamics.setAdapter(dynamicAdapter);

        // 添加滚动监听，实现分页加载
        rvMyDynamics.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();

                // 防止重复加载和处理最后一页
                if (isLoading || isLastPage) return;

                if (layoutManager != null &&
                        layoutManager.findLastVisibleItemPosition() >= dynamicList.size() - 2 && // 提前2个item开始加载
                        dy > 0) { // 确保是向下滚动
                    isLoading = true;
                    currentPage++;
                    fetchData(currentPage);
                }
            }
        });
    }

    private void deleteDynamic(int dynamicId, int position) {
        if (token == null) {
            Toast.makeText(this, "未获取到 token", Toast.LENGTH_SHORT).show();
            return;
        }

        // 调用删除API
        String url = DELETE_DYNAMIC_API + "/" + dynamicId;
        Request request = new Request.Builder()
                .url(url)
                .delete()
                .addHeader("Authorization", "Bearer " + token)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                new Handler(Looper.getMainLooper()).post(() ->
                        Toast.makeText(MyDynamicActivity.this, "删除失败，请重试", Toast.LENGTH_SHORT).show()
                );
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                new Handler(Looper.getMainLooper()).post(() -> {
                    if (response.isSuccessful()) {
                        // 从列表中移除并刷新
                        dynamicList.remove(position);
                        dynamicAdapter.notifyItemRemoved(position);
                        Toast.makeText(MyDynamicActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MyDynamicActivity.this, "删除失败，请重试", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    // 实现点赞功能
    private void likeDynamic(int dynamicId, int position, boolean isLiked) {
        if (token == null) {
            Toast.makeText(this, "未获取到 token", Toast.LENGTH_SHORT).show();
            return;
        }

        String url = RELEASE_DYNAMIC_API + "/" + dynamicId + "/like";
        Request.Builder requestBuilder = new Request.Builder().url(url);

        // 根据当前点赞状态决定是点赞还是取消点赞
        if (isLiked) {
            // 取消点赞
            requestBuilder.delete();
        } else {
            // 点赞
            requestBuilder.post(okhttp3.RequestBody.create(new byte[0])); // 空body
        }

        requestBuilder.addHeader("Authorization", "Bearer " + token);

        client.newCall(requestBuilder.build()).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                new Handler(Looper.getMainLooper()).post(() ->
                        Toast.makeText(MyDynamicActivity.this, "操作失败，请重试", Toast.LENGTH_SHORT).show()
                );
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                new Handler(Looper.getMainLooper()).post(() -> {
                    if (response.isSuccessful()) {
                        try {
//                            String responseData = response.body().string();
//                            JSONObject jsonResponse = new JSONObject(responseData);
//                            String message = jsonResponse.getString("message");
//                            Toast.makeText(MyDynamicActivity.this, message, Toast.LENGTH_SHORT).show();

                            // 更新UI状态
                            DynamicItem item = dynamicList.get(position);
                            boolean newLikedStatus = !isLiked;

                            // 更新点赞用户列表
                            List<Author> newLikers = new ArrayList<>(item.getLikers());
                            if (newLikedStatus) {
                                // 添加当前用户到点赞列表
                                SharedPreferences sp = getSharedPreferences("user_prefs", MODE_PRIVATE);
                                int userId = sp.getInt("id", -1);
                                String username = sp.getString("username", "我");
                                String avatar = sp.getString("avatar", null);
                                String gender = sp.getString("gender", "man");
                                String remark = sp.getString("remark", null);
                                String signs = sp.getString("signs", null);

                                Author currentUser = new Author(userId, username, avatar, gender, remark, signs);
                                newLikers.add(currentUser);
                            } else {
                                // 从点赞列表中移除当前用户
                                SharedPreferences sp = getSharedPreferences("user_prefs", MODE_PRIVATE);
                                int userId = sp.getInt("id", -1);
                                newLikers.removeIf(author -> author.getId() == userId);
                            }

                            // 创建更新后的DynamicItem
                            DynamicItem updatedItem = item.updateLikeStatus(newLikedStatus, newLikers);
                            dynamicAdapter.updateDynamicItem(position, updatedItem);
                        } catch (Exception e) {
                            Toast.makeText(MyDynamicActivity.this, "解析响应失败", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(MyDynamicActivity.this, "操作失败，请重试", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    // 实现评论发送功能
    private void sendComment(int dynamicId, int position, String commentContent) {
        if (token == null) {
            Toast.makeText(this, "未获取到 token", Toast.LENGTH_SHORT).show();
            return;
        }

        String url = RELEASE_DYNAMIC_API + "/" + dynamicId + "/comment";

        // 构造请求体
        JSONObject requestBody = new JSONObject();
        try {
            requestBody.put("content", commentContent);
        } catch (JSONException e) {
            e.printStackTrace();
            Toast.makeText(this, "构建请求失败", Toast.LENGTH_SHORT).show();
            return;
        }

        Request request = new Request.Builder()
                .url(url)
                .addHeader("Authorization", "Bearer " + token)
                .post(okhttp3.RequestBody.create(requestBody.toString(), MediaType.parse("application/json")))
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                new Handler(Looper.getMainLooper()).post(() ->
                        Toast.makeText(MyDynamicActivity.this, "评论发送失败，请重试", Toast.LENGTH_SHORT).show()
                );
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                new Handler(Looper.getMainLooper()).post(() -> {
                    if (response.isSuccessful()) {
                        try {
                            String responseData = response.body().string();
                            JSONObject jsonResponse = new JSONObject(responseData);
                            int code = jsonResponse.getInt("code");

                            if (code == 200) {
                                // 解析返回的评论数据
                                JSONObject commentData = jsonResponse.getJSONObject("data");
                                int commentId = commentData.getInt("id");

                                JSONObject authorJson = commentData.getJSONObject("author");
                                int authorId = authorJson.getInt("id");
                                String username = authorJson.getString("username");
                                String avatar = authorJson.optString("avatar", null);

                                String content = commentData.getString("content");
                                String createTime = commentData.getString("createTime");

                                // 获取当前用户的完整信息
                                SharedPreferences sp = getSharedPreferences("user_prefs", MODE_PRIVATE);
                                String gender = sp.getString("gender", "man");
                                String remark = sp.getString("remark", null);
                                String signs = sp.getString("signs", null);

                                Author commentAuthor = new Author(authorId, username, avatar, gender, remark, signs);
                                Comment newComment = new Comment(commentId, commentAuthor, content, createTime);

                                // 更新UI
                                DynamicItem item = dynamicList.get(position);
                                List<Comment> updatedComments = new ArrayList<>(item.getComments());
                                updatedComments.add(newComment);

                                DynamicItem updatedItem = item.updateComments(updatedComments);
                                dynamicAdapter.updateDynamicItem(position, updatedItem);

                                Toast.makeText(MyDynamicActivity.this, "评论发送成功", Toast.LENGTH_SHORT).show();
                            } else {
                                String message = jsonResponse.optString("message", "评论发送失败");
                                Toast.makeText(MyDynamicActivity.this, message, Toast.LENGTH_SHORT).show();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            Toast.makeText(MyDynamicActivity.this, "解析响应失败", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(MyDynamicActivity.this, "评论发送失败，请重试", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    // 实现评论删除功能
    private void deleteComment(int commentId, int dynamicPosition, int commentPosition) {
        if (token == null) {
            Toast.makeText(this, "未获取到 token", Toast.LENGTH_SHORT).show();
            return;
        }

        String url = RELEASE_DYNAMIC_API + "/comments/" + commentId;

        Request request = new Request.Builder()
                .url(url)
                .addHeader("Authorization", "Bearer " + token)
                .delete()
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                new Handler(Looper.getMainLooper()).post(() ->
                        Toast.makeText(MyDynamicActivity.this, "删除评论失败，请重试", Toast.LENGTH_SHORT).show()
                );
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                new Handler(Looper.getMainLooper()).post(() -> {
                    if (response.isSuccessful()) {
                        try {
                            String responseData = response.body().string();
                            JSONObject jsonResponse = new JSONObject(responseData);
                            int code = jsonResponse.getInt("code");

                            if (code == 200) {
                                // 更新UI
                                DynamicItem item = dynamicList.get(dynamicPosition);
                                List<Comment> updatedComments = new ArrayList<>(item.getComments());
                                updatedComments.remove(commentPosition);

                                DynamicItem updatedItem = item.updateComments(updatedComments);
                                dynamicAdapter.updateDynamicItem(dynamicPosition, updatedItem);

                                Toast.makeText(MyDynamicActivity.this, "评论删除成功", Toast.LENGTH_SHORT).show();
                            } else {
                                String message = jsonResponse.optString("message", "删除评论失败");
                                Toast.makeText(MyDynamicActivity.this, message, Toast.LENGTH_SHORT).show();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            Toast.makeText(MyDynamicActivity.this, "解析响应失败", Toast.LENGTH_SHORT).show();
                        }
                    } else if (response.code() == 403) {
                        Toast.makeText(MyDynamicActivity.this, "只有评论作者或动态发布者才能删除该评论", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MyDynamicActivity.this, "删除评论失败，请重试", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    @Override
    public void onImageClose() {
        rvZoomedImages.setVisibility(View.GONE);
    }

    private void loadInitialData() {
        currentPage = 0;
        isLastPage = false;
        dynamicList.clear();
        fetchData(currentPage);
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadInitialData();
    }

    private void fetchData(int page) {
        if (token == null) {
            Toast.makeText(this, "未获取到 token", Toast.LENGTH_SHORT).show();
            return;
        }

        String url = GET_FRIEND_DYNAMIC_API + "/" + userId + "?page=" + page + "&size=" + PAGE_SIZE;
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Authorization", "Bearer " + token)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                new Handler(Looper.getMainLooper()).post(() -> {
                    Toast.makeText(MyDynamicActivity.this, "网络错误，请稍后重试", Toast.LENGTH_SHORT).show();
                    isLoading = false;
                    if (swipeRefreshLayout != null && swipeRefreshLayout.isRefreshing()) {
                        swipeRefreshLayout.setRefreshing(false);
                    }
                });
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    String responseData = response.body().string();
                    try {
                        JSONObject jsonResponse = new JSONObject(responseData);
                        int code = jsonResponse.getInt("code");
                        if (code == 200) {
                            JSONObject data = jsonResponse.getJSONObject("data");
                            isLastPage = data.getBoolean("last");

                            List<DynamicItem> newData = DynamicFragment.parseDynamicItems(data.getJSONArray("content"));

                            new Handler(Looper.getMainLooper()).post(() -> {
                                if (page == 0) {
                                    dynamicList.clear();
                                }
                                dynamicList.addAll(newData);
                                dynamicAdapter.notifyDataSetChanged();
                                isLoading = false;
                                if (swipeRefreshLayout != null && swipeRefreshLayout.isRefreshing()) {
                                    swipeRefreshLayout.setRefreshing(false);
                                }
                            });
                        }
                    } catch (JSONException e) {
                        new Handler(Looper.getMainLooper()).post(() -> {
                            Toast.makeText(MyDynamicActivity.this, "解析数据失败", Toast.LENGTH_SHORT).show();
                            isLoading = false;
                            if (swipeRefreshLayout != null && swipeRefreshLayout.isRefreshing()) {
                                swipeRefreshLayout.setRefreshing(false);
                            }
                        });
                    }
                } else {
                    new Handler(Looper.getMainLooper()).post(() -> {
                        Toast.makeText(MyDynamicActivity.this, "获取动态失败", Toast.LENGTH_SHORT).show();
                        isLoading = false;
                        if (swipeRefreshLayout != null && swipeRefreshLayout.isRefreshing()) {
                            swipeRefreshLayout.setRefreshing(false);
                        }
                    });
                }
            }
        });
    }
}